﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Messaging;
using System.Net;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Script.Serialization;

namespace Derrick.Web
{


    public partial class CometService : System.Web.UI.Page
    {

        private TraceSwitch _proxySwitch = new TraceSwitch("CometProxy", "CometProxy");
        private MessageQueue _messageQueue = null;

        protected void Page_Load(object sender, EventArgs e)
        {

            System.Diagnostics.Trace.WriteLineIf(_proxySwitch.TraceVerbose, "Entering CometProxy.Page_Load().");
            byte[] bytes;
            using (Stream reader = Request.GetBufferlessInputStream())
            {
                bytes = new byte[reader.Length];
                reader.Read(bytes, 0, (int)reader.Length);
            }


            try
            {
                Response.ClearHeaders();
                Stream s = null;

                #region Comet Behaviour: Block on message queue

                string messageQueuePath = ConfigurationManager.AppSettings["CometQueue"];
                _messageQueue = new MessageQueue(messageQueuePath);
                Message msg = _messageQueue.Receive();  //holds thread until message received
                System.Diagnostics.Trace.WriteLineIf(_proxySwitch.TraceInfo, "Message retrieved from the message queue.");

                msg.Formatter = new XmlMessageFormatter(new Type[] { typeof(string) });
                string cometMsg = msg.Body.ToString();
                JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
                string jsonString = jsonSerializer.Serialize(cometMsg);
                byte[] jsonBytes = Encoding.ASCII.GetBytes(jsonString);
                s = new MemoryStream(jsonBytes);

                #endregion Comet Behaviour: Block on message queue

                string msgSizeStr = ConfigurationManager.AppSettings["MessageSize"];
                int messageSize = Convert.ToInt32(msgSizeStr);

                byte[] read = new byte[messageSize];
                // Reads 256 characters at a time.    
                int count = s.Read(read, 0, messageSize);
                while (count > 0)
                {
                    // Dumps the 256 characters on a string and displays the string to the console.
                    byte[] actualBytes = new byte[count];
                    Array.Copy(read, actualBytes, count);
                    //Response.BinaryWrite(actualBytes);
                    //string cometResponseStream = Encoding.UTF8.GetString(actualBytes);
                    string cometResponseStream = Encoding.ASCII.GetString(actualBytes);
                    //Response.Write(actualBytes);
                    Response.Write(cometResponseStream);
                    count = s.Read(read, 0, messageSize);
                }

                Response.End();
                System.Diagnostics.Trace.WriteLineIf(_proxySwitch.TraceVerbose, "Sent Message.");

                s.Close();
            }
            catch (Exception ex)
            {
                //Console.WriteLine(e.Message);
                System.Diagnostics.Trace.WriteLine("CometProxy Exception: " + ex.ToString());

            }



            System.Diagnostics.Trace.WriteLineIf(_proxySwitch.TraceVerbose, "Leaving CometProxy.Page_Load().");
            System.Diagnostics.Trace.Flush();
            System.Diagnostics.Trace.Close();
        }




    }
}